package com.example.sixth.coree.websocketservice;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.sixth.coree.task.SongTask;
import com.example.sixth.coree.utils.MiscUtil;
import com.example.sixth.coree.utils.SpringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundListOperations;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.CrossOrigin;

import javax.servlet.http.HttpServletRequest;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.ConcurrentHashMap;
@CrossOrigin
@ServerEndpoint(value = "/ws/{account}/{channel}/{ticket}")
@Component
public class core {
    public static ConcurrentHashMap<String, ConcurrentHashMap<String,Session>> CHATMAP =new ConcurrentHashMap<>();
    private  RedisTemplate redisTemplate=SpringUtils.getBean("redistemp");
    @OnOpen
    public void onOpen(Session session, @PathParam("account") String account, @PathParam("channel") String channel, @PathParam("ticket") String ticket) throws Exception {

        String s = MiscUtil.verifyToken(ticket);
        if (s != null && s.equals(channel)) {
            if (CHATMAP.get(channel) == null || CHATMAP.get(channel).isEmpty()) {
                CHATMAP.put(channel, new ConcurrentHashMap<>());
            }
            CHATMAP.get(channel).put(account, session);
            BoundListOperations boundListOperations = redisTemplate.boundListOps(channel);
            if (boundListOperations.size() != 0) {
                if (boundListOperations.size() != 0) {
                    JSONObject  song = JSON.parseObject(boundListOperations.index(0).toString());
                    song.put("since", (SongTask.channelhome.get(channel)==null?System.currentTimeMillis()+100:SongTask.channelhome.get(channel)) / 1000);
                    song.put("type", "playSong");
                    session.getBasicRemote().sendText(song.toJSONString());
                }
            }
        }
    }
    @OnMessage
    public void onMessage(Session session,String message,@PathParam("account") String account,@PathParam("channel") String channel){
         if(message.equals("bye")){
             onClose(session, account, channel);
         }
    }
    @OnClose
    public void onClose(Session session,@PathParam("account") String account,@PathParam("channel") String channel) {
        CHATMAP.get(channel).remove(account);
    }
}
